import { PlusOutlined, HomeOutlined, ClusterOutlined, CheckCircleOutlined, BankOutlined } from '@ant-design/icons';
import { Avatar, Card, Col, Divider, Input, Row, Tag, Popover } from 'antd';
import React, { Component, useState, useRef } from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { history, connect } from 'umi';
import Projects from './components/Projects';
import Articles from './components/Articles';
import Applications from './components/Applications';
import { RegionInfo } from '@/components/RegionSelect'
import { GenderIcon } from '@/components/UserBrief'
import { getDefaultAvatarUrl } from '@/utils/default'
import { addTag, removeTag } from '@/services/user'
import styles from './styles.less';
const operationTabList = [
  {
    key: 'articles',
    tab: (
      <span>
        文章{' '}
        <span
          style={{
            fontSize: 14,
          }}
        >
          (8)
        </span>
      </span>
    ),
  },
  {
    key: 'applications',
    tab: (
      <span>
        应用{' '}
        <span
          style={{
            fontSize: 14,
          }}
        >
          (8)
        </span>
      </span>
    ),
  },
  {
    key: 'projects',
    tab: (
      <span>
        项目{' '}
        <span
          style={{
            fontSize: 14,
          }}
        >
          (8)
        </span>
      </span>
    ),
  },
];

const TagList = ({ tags, dispatch }) => {
  const ref = useRef(null);
  const [newTags, setNewTags] = useState([]);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');

  const showInput = () => {
    setInputVisible(true);

    if (ref.current) {
      // eslint-disable-next-line no-unused-expressions
      ref.current?.focus();
    }
  };

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (inputValue == "" || inputValue.trim() === "") {
      setInputVisible(false);
      setInputValue('');
      return;
    }
    let tempsTags = [...newTags];
    addTag({
      name: inputValue
    }).then(({ data }) => {
      if (data) {
        tempsTags = [
          ...tempsTags,
          data,
        ];
        setNewTags(tempsTags);
        setInputVisible(false);
        setInputValue('');
      }
    })
  };

  const doRemoveTag = (item) => {
    console.log(item)
    let tempsTags = [...newTags];
    removeTag(item.id).then(({ success }) => {
      if (success) {
        setNewTags(tempsTags);
      }
    })
  }

  return (
    <div className={styles.tags}>
      <div className={styles.tagsTitle}>我的技能</div>
      {(tags || []).concat(newTags).map((item) => (
        <Tag key={item.id}
          closable
          onClose={() => {
            doRemoveTag(item)
          }}
        >{item.name}</Tag>
      ))}
      {inputVisible && (
        <Input
          ref={ref}
          type="text"
          size="small"
          style={{
            width: 78,
          }}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      )}
      {!inputVisible && (
        <Tag
          onClick={showInput}
          style={{
            borderStyle: 'dashed',
          }}
        >
          <PlusOutlined />
        </Tag>
      )}
    </div>
  );
};

class Center extends Component {

  state = {
    tabKey: 'articles',
  };
  input = undefined;

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/getMyDetail',
    });
    dispatch({
      type: 'enterprise/listUserEnterprise'
    });
    dispatch({
      type: 'enterprise/getUserCurrentEnterprise'
    });
    dispatch({
      type: 'accountAndcenter/fetch',
    });
  }

  onTabChange = (key) => {
    this.setState({
      tabKey: key,
    });
  };
  renderChildrenByTabKey = (tabKey) => {
    if (tabKey === 'projects') {
      return <Projects />;
    }

    if (tabKey === 'applications') {
      return <Applications />;
    }

    if (tabKey === 'articles') {
      return <Articles />;
    }

    return null;
  };
  renderUserInfo = (myDetail, currentEnterprise) => {
    if (!currentEnterprise || !currentEnterprise.enterprise || !myDetail) {
      return '';
    }
    let department = "-";
    if (currentEnterprise.enterpriseDepartment) {
      department = currentEnterprise.enterpriseDepartment.name;
      let currentDepartment = currentEnterprise.enterpriseDepartment.parentDepartment;
      while (currentDepartment) {
        department = currentDepartment.name + '-' + department;
        currentDepartment = currentDepartment.parentDepartment;
      }
    }
    return (
      <div className={styles.detail}>
        <div className={styles.enterpriseName}>
          <BankOutlined
            style={{
              marginRight: 8,
            }}
          />
          {currentEnterprise.enterprise.name}
        </div>
        <div className={styles.enterpriseInfoClass}>
          <ClusterOutlined
            style={{
              marginRight: 8,
            }}
          />
          <div>{currentEnterprise.enterpriseRoleName}</div>
          <div className={styles.departmentInfo}>{`-${department}`}</div>
        </div>
        <div className={styles.regionClass}>
          <HomeOutlined
            style={{
              marginRight: 8,
            }}
          />
          <RegionInfo provinceId={myDetail.provinceId} cityId={myDetail.cityId}></RegionInfo>
        </div>
      </div>
    );
  }



  render() {
    const { dispatch } = this.props;
    const { tabKey } = this.state;
    const { myDetail, myDetailLoading, userEnterpriseList, currentEnterprise } = this.props;
    const dataLoading = myDetailLoading || !(myDetail);
    return (
      <GridContent>
        <Row gutter={24}>
          <Col lg={7} md={24}>
            <Card
              bordered={false}
              style={{
                marginBottom: 24,
              }}
              loading={dataLoading}
            >
              {!dataLoading && (
                <div>
                  <div className={styles.avatarHolder}>
                    <img alt="" src={myDetail.avatarUrl || getDefaultAvatarUrl(myDetail.ids)} />
                    <div className={styles.name}>
                      {myDetail.nickName || myDetail.username}
                      <GenderIcon gender={myDetail.gender} className={styles.gender} ></GenderIcon>
                    </div>
                    <div>{myDetail.motto}</div>
                  </div>
                  {this.renderUserInfo(myDetail, currentEnterprise)}
                  <Divider dashed />
                  <TagList tags={myDetail.tags || []} dispatch={dispatch} />
                  <Divider
                    style={{
                      marginTop: 16,
                    }}
                    dashed
                  />
                  <div className={styles.enterprise}>
                    <div className={styles.enterpriseTitle}>企业团队</div>
                    <Row gutter={36}>
                      {userEnterpriseList &&
                        userEnterpriseList.map((item) => (
                          <Col key={item.id} lg={24} xl={12} >
                            <Popover className={styles.enterpriseItem}
                              content={<a onClick={() => {
                                const { dispatch } = this.props;
                                if (dispatch && item.isCurrent === 0) {
                                  dispatch({
                                    type: 'enterprise/setCurrentEnterprse',
                                    payload: item
                                  }).then((success) => {
                                    if (success) {
                                      history.push("/");
                                    }
                                  });
                                } else {
                                  history.push("/");
                                }
                              }}>{item.isCurrent === 1 ? '查看' : '设置为你当前企业并查看'}</a>}
                              placement="bottom"
                              trigger="click"
                            >
                              <Avatar src={item.enterprise.icon} />
                              <div>
                                <div className={styles.enterpriseName}>{item.enterprise.name}</div>
                                {item.isCurrent === 1 ?
                                  (<Tag icon={<CheckCircleOutlined />} color="#87d068" size="small">{item.enterpriseRoleName}</Tag>) :
                                  (<Tag color="#55acee" size="small">{item.enterpriseRoleName}</Tag>)
                                }

                              </div>
                            </Popover>
                          </Col>
                        ))}
                    </Row>
                  </div>
                </div>
              )}
            </Card>
          </Col>
          <Col lg={17} md={24}>
            <Card
              className={styles.tabsCard}
              bordered={false}
              tabList={operationTabList}
              activeTabKey={tabKey}
              onTabChange={this.onTabChange}
            >
              {this.renderChildrenByTabKey(tabKey)}
            </Card>
          </Col>
        </Row>
      </GridContent>
    );
  }
}

export default connect(({ user, loading, enterprise }) => ({
  myDetail: user.myDetail,
  currentEnterprise: enterprise.currentEnterprise,
  userEnterpriseList: enterprise.userEnterpriseList,
  myDetailLoading: loading.effects['user/getMyDetail'],
}))(Center);
